package com.tl.web05.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 字符编码filter
 */
@WebFilter(urlPatterns = "/*")
public class EncodingFilter extends HttpFilter {
    private final List<String> notFilterList = Arrays.asList("/captcha", ".js", ".css");

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {

        try {
            String servletPath = req.getServletPath();
            for (String s : notFilterList) {
                if (servletPath.endsWith(s)) {
                    chain.doFilter(req, res);
                    return;
                }
            }
            req.setCharacterEncoding("utf-8");
            res.setCharacterEncoding("utf-8");
            chain.doFilter(req, res);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
